from selenium.webdriver.remote.webdriver import WebDriver, WebElement
from utils.selenium.perform import WPerform, FindType


def run(perform: WPerform, query: dict or list):
    perform.sleep(3)
    for menus in query:
        click_menu(menus.get('title'), menus.get('subtitle'), perform)
        perform.sleep(3)


def check_is_vue(perform: WPerform):
    """
    是否是Vue 项目
    :return:
    """
    return '-vue' in perform.driver.current_url


def click_menu(super_title: str, sub_title: str, perform: WPerform):
    """
    菜单点击
    :param super_title:
    :param sub_title:
    :param perform:
    :return:
    """
    is_vue = check_is_vue(perform)
    # 父菜单的css
    super_menu_class = 'li.el-submenu' if is_vue else 'li.ant-menu-submenu.ant-menu-submenu-inline'
    # 是否展开的class
    open_class = 'is-opened' if is_vue else 'ant-menu-submenu-open'
    # 查询父菜单
    super_element = find_element_with_title(super_title, perform, super_menu_class)
    if not super_element:
        raise Exception('模块【%s】未找到' % super_title)
    # 获取父元素的clsss
    super_class = super_element.get_attribute('class')
    if open_class not in super_class:
        super_element.click()
    perform.sleep(2)
    # 子菜单的class
    sub_menu_class = 'li.el-menu-item' if is_vue else 'li.ant-menu-item'
    # 获取子菜单
    sub_element = find_element_with_title(sub_title, perform, sub_menu_class)
    # 点击子菜单
    if not sub_element:
        raise Exception('菜单【%s】未找到' % sub_title)
    sub_element.click()


def find_element_with_title(title: str, perform: WPerform, find_class: str, super_element=None):
    elements: list = perform.fint(find_type=FindType.css,
                                  find_key=find_class,
                                  multiple=True,
                                  highlighted=False,
                                  super_element=super_element)
    for element in elements:
        if title in element.text:
            return element
